﻿
<div class="modal fade" id="registermodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">注册新账号</h4>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
          &times;
        </button>

      </div>
      <div class="modal-body">
        <form id="registuser_form" class="needs-validation" novalidate>
          <input id="Id" name="Id" type="hidden" value="" />
          <div class="row no-gutters row-grid">
            <div class="col-12">
              <div class="d-flex flex-column align-items-center justify-content-center pb-4">
                <div class="avatars">
                  <img id="avatar_lg" src="~/img/avatars/@(ViewBag.Avatar)" asp-append-version="true"
                       style="width:129.5px"
                       class="rounded-circle shadow-2 img-thumbnail" alt="">

                  <div class="overlay">
                    <div class="text">
                      <h5 class="mb-0 fw-700 text-center mt-3">
                        单击修改照片
                      </h5>
                    </div>
                  </div>
                  <input type="file" name="upload_avatar" class="image" id="upload_avatar" style="display:none" />
                </div>
              </div>
            </div>
          </div>

          <div class="form-row form-group">
            <div class="col-md-6">
              <label class="form-label" for="userName">用户名</label>
              <input type="text" class="form-control" id="userName" name="userName" pattern="^[\u4E00-\u9FA5a-zA-Z0-9_]{2,20}$" required>
              <div class="invalid-feedback">
                请输入有效的用户名
              </div>
            </div>
            <div class="col-md-6">

              <label class="form-label" for="givenName">昵称</label>
              <input type="text" class="form-control" id="givenName" name="givenName" pattern="^[\u4E00-\u9FA5a-zA-Z0-9_]{2,20}$" required>
              <div class="invalid-feedback">
                请输入有效的昵称
              </div>

            </div>
          </div>
          <div class="form-row form-group">
            <div class="col-md-6">
              <label class="form-label" for="password">新密码</label>
              <input type="password" class="form-control" id="password" name="password" required minlength="4">
              <div class="invalid-feedback">
                请输入新密码
              </div>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="passwordConfirm">再输入新密码</label>
              <input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm" required minlength="4">
              <div class="invalid-feedback">
                请输入正确的密码
              </div>
            </div>
          </div>
          <div class="form-row form-group">
            <div class="col-md-6">
              <label class="form-label" for="newemail">邮件地址</label>
              <input type="email" class="form-control" id="newemail" name="newemail" required>
              <div class="invalid-feedback">
                请输入邮件地址
              </div>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="phonenumber">联系电话</label>
              <input type="number" class="form-control" id="phonenumber" name="phonenumber">
            </div>
          </div>
          <div class="form-row form-group">
            <div class="col-md-6">
              <label class="form-label" for="tenantid">租户</label>
              @Html.DropDownList("tenantid", (IEnumerable
        <SelectListItem>)ViewBag.tenantid, new { @class = "form-control", required = "required" })

              <div class="invalid-feedback">
                请选择租户
              </div>
            </div>
          </div>
        </form>
        <script>
          // Example starter JavaScript for disabling form submissions if there are invalid fields
          (function () {
            'use strict';
            window.addEventListener('load', function () {
              // Fetch all the forms we want to apply custom Bootstrap validation styles to
              var txtPassword = document.getElementById("password");
              var txtConfirmPassword = document.getElementById("passwordConfirm");
              txtPassword.onchange = ConfirmPassword;
              txtConfirmPassword.onkeyup = ConfirmPassword;
              function ConfirmPassword() {
                txtConfirmPassword.setCustomValidity("");
                if (txtPassword.value != txtConfirmPassword.value) {
                  txtConfirmPassword.setCustomValidity("新密码不匹配.");
                }
              }
            }, false);
          })();

        </script>



      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">
          取消
        </button>
        <button type="button" onclick="saveuser()" name="savebutton" class="btn btn-primary">
          注册
        </button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div>

<div class="modal fade copper-modal-right" tabindex="-1" role="dialog" aria-modal="true" aria-hidden="true">
  <div class="modal-dialog modal-dialog-right  ">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title h4">修改照片</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true"><i class="fal fa-times"></i></span>
        </button>
      </div>
      <div class="modal-body">
        <div class="panel-container show">
          <div class="panel-content">
            <div class="row">
              <div class="col-12">
                <div class="img-container">

                  <img id="upload_avatar_image" />
                </div>
              </div>

            </div>
          </div>
        </div>

        <div class="card mb-g">
          <div class="card-body p-3">
            <div class="row">
              <div class="col-12">
                <div class="docs-preview clearfix">
                  <div class="img-preview preview-lg"></div>
                  <div class="img-preview preview-md"></div>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary waves-effect waves-themed" data-dismiss="modal">Close</button>
        <button type="button" id="getcoppedbutton" class="btn btn-primary waves-effect waves-themed">确认</button>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function () {
    let image = document.getElementById('upload_avatar_image');
    let avatarimg = document.getElementById('avatar_lg');

    let av = document.getElementById('upload_avatar_image');
    let $modal = $('.copper-modal-right');
    let cropper = null;
    $('.avatars > .overlay').click(function () {
      document.getElementById('upload_avatar').click();
    })
    $(document).on('show.bs.modal', '.modal', function (event) {
      var zIndex = 1040 + (10 * $('.modal:visible').length);
      $(this).css('z-index', zIndex);
      setTimeout(function () {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
      }, 0);
    });
    $modal.on('shown.bs.modal', function () {
      cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 1,
        preview: '.img-preview',
        width: 120,
        height: 120,
      });
    }).on('hidden.bs.modal', function () {
      cropper.destroy();
      cropper = null;
    });
    $('#upload_avatar').change(function (event) {
      var files = event.target.files;
      var done = function (url) {
        image.src = url;
        $modal.modal('toggle')
      };
      if (files && files.length > 0) {
        reader = new FileReader();
        reader.onload = function (event) {
          done(reader.result);
        };
        reader.readAsDataURL(files[0]);
      }
    });
    $('#getcoppedbutton').click(function () {

      const imageData = cropper.getImageData();
      const base64str = cropper.getCroppedCanvas().toDataURL();
      avatarimg.src = base64str;
      //console.log(imageData, canvasData)
    });
  });
  function showregisterform() {
    $('#registermodal').modal('toggle');
    document.getElementById("registuser_form").reset();
    $('#registuser_form #userName').prop('readonly', false);
    $('#registuser_form #password').prop('readonly', false);
    $('#registuser_form #passwordConfirm').prop('readonly', false);
    $('#registuser_form #Id').val('');
    $("#registuser_form #avatar_lg").attr('src', `/img/avatars/avatar-lg.jpg`);
    $('button[name="savebutton"]').text('注册')
  }
  function showedituserform(user) {
    $('#registermodal').modal('toggle');
    document.getElementById("registuser_form").reset();
    $('#registuser_form #password').prop('readonly', true);
    $('#registuser_form #passwordConfirm').prop('readonly', true);
    $('#registuser_form #Id').val(user.Id);
    $('#registuser_form #userName').val(user.UserName);
    $('#registuser_form #userName').prop('readonly', true);
    $('#registuser_form #givenName').val(user.GivenName);
    $('#registuser_form #newemail').val(user.Email);
    $('#registuser_form #tenantid').val(user.TenantId);
    $('#registuser_form #phonenumber').val(user.PhoneNumber);
    $("#registuser_form #avatar_lg").attr('src', `/img/avatars/${user.AvatarUrl}`);
    $('button[name="savebutton"]').text('更新')

  }
  function saveuser() {
    var form = document.getElementById("registuser_form");
    if (form.reportValidity()) {
      if ($('button[name="savebutton"]').text() == '注册') {
        var url = "/AccountManage/ReregisterUser"

        $.post(url, {
          model: {
            Username: $('#registuser_form #userName').val(),
            Email: $('#registuser_form #newemail').val(),
            TenantId: $('#registuser_form #tenantid').val(),
            Password: $('#registuser_form #password').val(),
            PasswordConfirm: $('#registuser_form #passwordConfirm').val(),
            GivenName: $('#registuser_form #givenName').val(),
            PhoneNumber: $('#registuser_form #phonenumber').val(),
            Avatar: getavatarbase64(),
          }
        }).done((res) => {
          if (res.success) {
            $('#registermodal').modal('toggle');
            reloadData();
          } else {
            $.messager.alert('错误', res.err)
          }
        });
      } else {
        var url = "/AccountManage/UpdateUser"
        $.post(url, {
          model: {
            Id: $('#registuser_form #Id').val(),
            Email: $('#registuser_form #newemail').val(),
            TenantId: $('#registuser_form #tenantid').val(),
            GivenName: $('#registuser_form #givenName').val(),
            PhoneNumber: $('#registuser_form #phonenumber').val(),
            Avatar: getavatarbase64(),
          }
        }).done((res) => {
          if (res.success) {
            $('#registermodal').modal('toggle');
            reloadData();
          } else {
            $.messager.alert('错误', res.err, 'error')
          }
        });
      }

    } else {
      form.classList.add('was-validated');
    }

  }
  function getavatarbase64() {
    var canvas = document.createElement('canvas');
    var img = document.getElementById('avatar_lg');
    canvas.height = img.naturalHeight;
    canvas.width = img.naturalWidth;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var base64String = canvas.toDataURL();
    return base64String;
  }
</script>
